var express = require('express');
var router = express.Router();
var { TestModel } = require('../model/model')
let alipaySdk = require('../alipay')
let AlipayFormData = require('alipay-sdk/lib/form').default
const {ChatCompletion,setEnvVariable} = require('@baiducloud/qianfan')

// 设置百度云千帆的API Key和Sercret Key
setEnvVariable('QIANFAN_AK', '9lFqOXYm08vIooie9OpaiUIO');
setEnvVariable('QIANFAN_SK', 'ZW4BlEcjgHhTZDOxXtmsbiNVzB5irdxV');


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

//数据库测试
router.post('/addtest', (req, res)=>{
  TestModel.create(req.body)
  res.send({
    status: 200,
    message: "success"
  })
})

// ----------姜文浩---------------
// ----------随机订单号---------------
function randomCodes(){
  var code = ""
  var codeLength = 7;
  var random = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  for(var i = 0;i < codeLength; i++){
    code += Math.floor(Math.random()*random.length);
  }
}
// ----------支付功能---------------
router.post('/api/pay',async (req,res)=>{
  let form = req.body;
  console.log(form)
  const formData = new AlipayFormData();
  formData.setMethod('get');
  formData.addField('returnUrl','pages/index/index')//  支付成功后跳转的页面
  formData.addField('bizContent',{
    out_trade_no:randomCodes(),//  订单号
    product_code:'FAST_INSTANT_TRADE_PAY',//  销售产品码，与支付宝签约的产品码保持一致
    total_amount:form.price,//  订单总金额，单位为元，精确到小数点后两位
    subject:form.name,//  订单标题
    body:form.name//  订单描述
  });
  //  返回promise
  const result =  await alipaySdk.exec(
    'alipay.trade.wap.pay',//  调用手机端的支付接口
    {},// 公共参数
    {formData:formData}// 业务参数result为可以跳转支付链接的url
  );
  console.log('result',result)
  res.send({
    code:200,
    result
  })
})

// ----------AI对话---------------

const client = new ChatCompletion({Endpoint:'completions_pro'})
router.post('/api/char',async (req,res)=>{
  const {messages} = req.body;
  console.log(req.body)
  const resp = await client.chat({messages})
  console.log('resp',resp)
  res.send({
    result:resp.result
  })
})


// ----------姜文浩---------------

module.exports = router;
